package com.edu.hbwe.book.service.impl;

import java.sql.SQLException;
import java.util.List;
import com.edu.hbwe.book.dao.OrderDao;
import com.edu.hbwe.book.dao.OrderItemDao;
import com.edu.hbwe.book.dao.ProductDao;
import com.edu.hbwe.book.dao.impl.OrderDaolmpl;
import com.edu.hbwe.book.dao.impl.OrderltemDaolmpl;
import com.edu.hbwe.book.dao.impl.ProductDaoImpl;
import com.edu.hbwe.book.entity.Order;
import com.edu.hbwe.book.entity.OrderItem;
import com.edu.hbwe.book.entity.User;
import com.edu.hbwe.book.exception.OrderException;
import com.edu.hbwe.book.service.OrderService;
import com.edu.hbwe.book.util.DbUtil;




public class OrderServicelmpl implements OrderService {

	private OrderDao odao = new OrderDaolmpl();
	private OrderItemDao oidao = new OrderltemDaolmpl(); 
	private ProductDao pdao = new ProductDaoImpl();

	// 查找所有订单
	public List<Order> findAllOrder() {
		// 查找出订单信息
		List<Order>	orders = odao.findAllOrder();

		return orders;
	}

	//条件查询订单
	public List<Order> findOrderByManyCondition(String id, String receiverName) {

		List<Order>	orders = odao.findOrderByManyCondition(id, receiverName);

		if (orders==null) 
			throw new RuntimeException("查询失败！");
		return orders;
	}

	//根据id查询单个订单
	public Order findOrderById(String id) {
		Order order = null;
		order = odao.findOrderById(id);
		List<OrderItem> items = oidao.findOrderItemByOrder(order);
		order.setOrderItems(items);
		return order;
	}

	//管理员删除订单
	public void delOrderById(String id) {			
		try {
			DbUtil.startTransaction();//开启事务
			oidao.delOrderItems(id);
			odao.delOrderById(id);
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				DbUtil.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		}finally{
			try {
				DbUtil.releaseAndCloseConnection();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}		
	}

	@Override
	public void updateState(String orderid) throws OrderException {
		int row = odao.updateOrderState(orderid);
		if(row == 0)
			throw new OrderException("订单状态修改失败");
	}

	@Override
	public void addOrder(Order order) {
		try {
			// 1.开启事务
			DbUtil .startTransaction();
			// 2.完成操作
			// 2.1向orders表中添加数据
			odao.addProduct(order);
			// 2.2向orderItem表中添加数据
			oidao.addOrderItem(order);
			// 2.3修改商品表中数据.
			pdao.changeProductNum(order);
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				DbUtil.rollback(); // 事务回滚
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		} finally {
			try {
				// 关闭，释放以及提交事务
				DbUtil.releaseAndCloseConnection();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}


	@Override
	public List<Order> findOrderByUser(User user) {
		List<Order> orders = odao.findOrderByUser(user);
		return orders;
	}








}
